package com.tanhua.common.service.impl;

import com.aliyun.oss.OSSClient;
import com.tanhua.common.config.AliyunOssConfig;
import com.tanhua.common.service.OssUploadService;
import com.tanhua.common.utils.OssUploadUtils;
import com.tanhua.common.vo.PicUploadResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;

/**
 * @author ldp
 * @date 2021/4/2614:16
 */
@Service
@Slf4j
public class OssUploadServiceImpl implements OssUploadService {

    @Autowired
    private OSSClient ossClient;

    @Autowired
    private AliyunOssConfig aliyunConfig;
    /**
     * 上传图片
     * @param uploadFile
     * @return
     */
    @Override
    public PicUploadResult upload(MultipartFile uploadFile) {
        PicUploadResult fileUploadResult = new PicUploadResult();
        String filepath="";
        //调用工具类
        try {
            filepath = OssUploadUtils.uploadFileOss(uploadFile);
            if(filepath==null){
                fileUploadResult.setStatus("error");
                return fileUploadResult;
            }
            //上传阿里云oss
            ossClient.putObject(aliyunConfig.getBucketName(),filepath,new ByteArrayInputStream(uploadFile.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }
        //上传成功
        fileUploadResult.setStatus("done");
        fileUploadResult.setName(aliyunConfig.getUrlPrefix()+ filepath);
        fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        return fileUploadResult;
    }
}